package com.chainyoung.trademarket.ui;


import android.content.DialogInterface;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.adpter.BaseFragmentAdapter;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.trademarket.R;
import com.chainyoung.trademarket.di.component.DaggerMainComponent;
import com.chainyoung.trademarket.di.module.MainModule;
import com.chainyoung.trademarket.entity.MsgNum;
import com.chainyoung.trademarket.mvp.contract.MsgCenterContract;
import com.chainyoung.trademarket.mvp.presenter.MsgCenterPresenter;
import com.chainyoung.trademarket.ui.fragment.MessageFragment;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;

import static com.chainyoung.router.RouterConstants.PATH_MESSAGE_CENTER;
import static com.chainyoung.trademarket.ui.fragment.MessageFragment.ADMIN_MSG;
import static com.chainyoung.trademarket.ui.fragment.MessageFragment.CHAT_MSG;
import static com.chainyoung.trademarket.ui.fragment.MessageFragment.ORDER_MSG;

//消息中心

@Route(path = PATH_MESSAGE_CENTER)
public class MessageCenterActivity extends BaseActivity<MsgCenterPresenter> implements MsgCenterContract.View {

    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;

    private String[] titles = {"系统消息", "订单消息", "聊天消息"};
    private List<Fragment> fragmentList = new ArrayList<>();
    private boolean isUnreadNum;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent.builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        showAndSetBarRightText(getString(R.string.all_read));
        setCurrentTitle(getString(R.string.msg_center));
        setFragments();
        initViewPager();
        setListener();
    }

    private void setListener() {

    }

    private void setFragments() {
        fragmentList.add(MessageFragment.newInstance(ADMIN_MSG));
        fragmentList.add(MessageFragment.newInstance(ORDER_MSG));
        fragmentList.add(MessageFragment.newInstance(CHAT_MSG));
    }

    private void setTabs() {
        for (int mI = 0; mI < titles.length; mI++) {
            TabLayout.Tab mTab = tabLayout.getTabAt(mI);
            View mView = LayoutInflater.from(this).inflate(R.layout.layout_msg_tab, null);
            TextView mTabText = mView.findViewById(R.id.tv_tab_name);
            TextPaint tp = mTabText.getPaint();
            tp.setFakeBoldText(true);
            TextView mTabNum = mView.findViewById(R.id.tv_msg_num);
            mTabText.setText(titles[mI]);
            if (mTab != null) {
                mTab.setCustomView(mView);
            }
        }

    }

    private void initViewPager() {
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        viewPager.setOffscreenPageLimit(titles.length);
        viewPager.setAdapter(new BaseFragmentAdapter(getSupportFragmentManager(), fragmentList));
        tabLayout.setupWithViewPager(viewPager);
        viewPager.setOffscreenPageLimit(titles.length);
        viewPager.setCurrentItem(0);
        setTabs();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_msg_center;
    }

    @Override
    public void onRightTxtClicked(View v) {
        if (!isUnreadNum) {
            ToastUtil.showToast(getString(R.string.no_unread_msg));
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(R.string.confirm_clear_unread_remind)
                .setPositiveButton(mContext.getString(com.chainyoung.component_tmtrade.R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearUnread();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(mContext.getString(com.chainyoung.component_tmtrade.R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create();
        builder.show();


    }

    private void clearUnread() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("operation", "read");
        map.put("read_all", true);
        map.put("msg_type", "admin");
        mPresenter.updateMsgStatus(map);
    }

    @Override
    public void onUpdateMsgStatus(MsgNum data) {
        //清除未读消息提示
        for (int i = 0; i < titles.length; i++) {
            View view = tabLayout.getTabAt(i).getCustomView();
            TextView tvNumView = view.findViewById(R.id.tv_msg_num);
            tvNumView.setVisibility(View.GONE);
            tvNumView.setText("");
        }
        ((MessageFragment) fragmentList.get(viewPager.getCurrentItem())).refreshData();
        isUnreadNum = false;
        EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.CLEAR_MSG));
    }

    @Subscriber
    public void onUpdateMsgNum(BaseEvent event) {
        isUnreadNum = false;
        if (event.getCode() == BaseEvent.EventCode.MSG_NUM) {
            HashMap<String, Integer> map = (HashMap<String, Integer>) event.getData();
            //CommonList<Msg> msg = (CommonList<Msg>)
            if (map.containsKey(ADMIN_MSG)) {
                View view = tabLayout.getTabAt(0).getCustomView();
                TextView tvNumView = view.findViewById(R.id.tv_msg_num);
                tvNumView.setVisibility(map.get(ADMIN_MSG) == 0 ? View.GONE : View.VISIBLE);
                tvNumView.setText(map.get(ADMIN_MSG) > 99 ? "99+" : map.get(ADMIN_MSG) + "");
                if (map.get(ADMIN_MSG) > 0) {
                    isUnreadNum = true;
                }

            }
            if (map.containsKey(ORDER_MSG)) {
                View view1 = tabLayout.getTabAt(1).getCustomView();
                TextView tvNumView1 = view1.findViewById(R.id.tv_msg_num);
                tvNumView1.setVisibility(map.get(ORDER_MSG) == 0 ? View.GONE : View.VISIBLE);
                tvNumView1.setText(map.get(ORDER_MSG) > 99 ? "99+" : map.get(ORDER_MSG) + "");
                if (map.get(ORDER_MSG) > 0) {
                    isUnreadNum = true;
                }
            }
            if (map.containsKey(CHAT_MSG)) {
                View view2 = tabLayout.getTabAt(2).getCustomView();
                TextView tvNumView2 = view2.findViewById(R.id.tv_msg_num);
                tvNumView2.setVisibility(map.get(CHAT_MSG) == 0 ? View.GONE : View.VISIBLE);
                tvNumView2.setText(map.get(CHAT_MSG) > 99 ? "99+" : map.get(CHAT_MSG) + "");
                if (map.get(ORDER_MSG) > 0) {
                    isUnreadNum = true;
                }
            }
        }
    }


}


